package com.container.registration;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletException;

import com.container.core.MyServletContext;

import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.LinkedList;

public class MyFilterRegistration extends AbstractNettyRegistration implements FilterRegistration.Dynamic {
    private Filter filter;
    private volatile boolean initialized;//用来实现懒加载
    private Collection<String> urlMappings = new LinkedList<>();

    public MyFilterRegistration(MyServletContext context, String filterName, String className, Filter filter) {
        super(filterName, className, context);
        this.filter = filter;
    }

    public Filter getFilter() throws ServletException {
        if (!initialized) {
            synchronized (this) {
                if (!initialized) {
                    if (filter == null) {
                        try {
                            filter = (Filter) Class.forName(getClassName()).newInstance();
                        } catch (Exception e) {
                            throw new ServletException(e);
                        }
                    }
                    filter.init(this);
                    initialized = true;
                }
            }
        }
        return filter;
    }

    @Override
    public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... patterns) {
        MyServletContext context = getNettyContext();
        for (String p : patterns) {
            context.addFilterMapping(dispatcherTypes, isMatchAfter, p);
        }
        urlMappings.addAll(Arrays.asList(patterns));
    }

    @Override
    public Collection<String> getUrlPatternMappings() {
        return urlMappings;
    }

    @Override
    public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {}

    @Override
    public Collection<String> getServletNameMappings() {
        return null;
    }
}
